<template>
  <view class="choose-community-page">
    <!-- 顶部城市选择和搜索框 -->
    <view class="header">
      <view class="city-select" @click="showCityPicker = true">
        <text class="u-m-r-10">{{ cityName ||"请选择城市" }}</text>
        <u-icon name="arrow-down" size="13" color="#999"></u-icon>
      </view>
      <input class="search-input" v-model="searchValue" placeholder="搜索小区" />
    </view>

    <view class="community-title">切换小区</view>
    <view class="community-list">
      <view
        v-for="(item, idx) in communityList"
        :key=" idx"
        class="community-item"
        :class="{ 'selected-community': isCurrentCommunity(item) }"
        @click="handleCommunityClick(item)"
      >
      <view class="w-full u-flex u-row-between">
        <text class="community-name">{{ item.name }}</text>
        <text v-if="isCurrentCommunity(item)" class="current-tag">当前</text>
      </view>
      <view class="u-m-t-10" v-if="item.address">
        <text class="community-address line-1">{{ item.address }}</text>
      </view>
        
      </view>
      <u-loadmore :status="status" />
    </view>

    <!-- 底部按钮 -->
    <view class="not-found-btn-wrapper" @click="handleNotFoundClick">
      <view class="not-found-btn">找不到您的小区？</view>
    </view>
    <u-picker
      :immediateChange ="true"
      :show="showCityPicker"
      ref="cityPicker"
      :columns="cityColumns"
      @confirm="onCityConfirm"
      @cancel="showCityPicker = false"
      @change="onCityChange"
      title="选择城市"
    />
  </view>
</template>

<script>
import { getCommunity } from '@/api/index'
import { getAreas } from '@/api' // 假设接口同 joinTrial
import { mapState,mapMutations } from 'vuex'
export default {
  data() {
    return {
      communityList: [],
      page: 1,
      pageSize: 10,
      status: 'loadmore', // loadmore/loading/nomore
      total: 0,
      // 省市选择相关
      showCityPicker: false,
      cityColumns: [[], []],
      cityData: [],
      selectedCity: {
        province: '',
        city: '',
        provinceCode: '',
        cityCode: ''
      },
      cityName: '',
      searchValue:''
    }
  },
  computed:{
    ...mapState('community',['location','communityId'])
  },
  watch:{
    searchValue(newVal){
      this.selectedCity.name=newVal;
      this.$nextTick(()=>{
        this.fetchCommunityList(true);
      })
    }
  },
  onLoad() {
    // this.initCityData();
    // this.fetchCommunityList(true);
    this.init();
  },
  onReachBottom() {
    if(this.communityList.length >= this.total){
      this.status = 'nomore';
    }else{
      this.fetchCommunityList(false);
    }
  },
  methods: {
    ...mapMutations("community",["setBoundHouses","setCommunityName","setCommunityId"]),
    isCurrentCommunity(item) {
      return item.communityId === this.communityId;
    },
    handleNotFoundClick(){
      uni.navigateTo({
        url: '/pages/joinTrial/index'
      })
    },
    init(){
      this.initCityData();
     
      // this.cityName=this.location.province
      // this.selectedCity.province=this.location.province
      // this.selectedCity.provinceCode=this.location.provinceCode 
      // this.selectedCity.cityCode=this.location.cityCode 
      this.fetchCommunityList(true);
    },
    handleCommunityClick(item) {
      // this.$store.commit('community/setCommunityId',item.communityId)
      // this.$store.commit('community/setCommunityName',item.name)
      console.log("item.communityId",item.communityId)
      this.setCommunityId(item.communityId.toString())
      this.setCommunityName(item.name)
      this.setBoundHouses(0) //切换小区后，绑定房子数量清零
      uni.switchTab({
        url: '/pages/home/index?communityId='+item.communityId,
        data:{
          communityId:item.communityId
        }
      })
    },
    async initCityData() {
      let res = await getAreas({});
      this.cityData = res.rows || [];
      // 初始化 picker 数据
      const provinces = this.cityData.map(province => ({
        text: province.name,
        value: province.id
      }));
      const cities = this.cityData[0]?.children?.map(city => ({
        text: city.name,
        value: city.id
      })) || [];
      this.cityColumns = [provinces, cities];
    },
    onCityChange(e) {
      const { columnIndex, index } = e;
      if (columnIndex === 0) {
        const selectedProvince = this.cityData[index];
        const cities = selectedProvince?.children?.map(city => ({
          text: city.name,
          value: city.id
        })) || [];
        this.$refs.cityPicker.setColumnValues(1, cities);
      }
    },
    onCityConfirm(e) {
      const [province, city] = e.value;
      this.cityName = city.text;
      this.selectedCity = {
        province: province.text,
        city: city.text,
        provinceCode: province.value,
        cityCode: city.value
      };
      this.$store.commit('community/setLocation',this.selectedCity)
      this.showCityPicker = false;
      // 选中地区后自动搜索
      this.fetchCommunityList(true);
    },
    async fetchCommunityList(isInit = false) {
      // if (this.status === 'loading' || this.status === 'nomore') return;
      this.status = 'loading';
      if (isInit) {
        this.page = 1;
        this.communityList = [];
      } else {
        this.page++;
      }
      // 带上省市code参数
      const params = {
        pageNum: this.page,
        pageSize: this.pageSize,
        provinceCode: this.selectedCity.provinceCode,
        cityCode: this.selectedCity.cityCode,
        name:this.searchValue
      };
      const res = await getCommunity(params);
      if (res && Array.isArray(res.rows) && res.rows.length > 0) {
        if (isInit) {
          this.communityList = res.rows;
        } else {
          this.communityList = this.communityList.concat(res.rows);
        }
        this.total = res.total || this.communityList.length;
        this.status = this.communityList.length >= this.total ? 'nomore' : 'loadmore';
      } else {
        if (isInit) {
          this.communityList = [];
        }
        this.status = 'nomore';
      }
    }
  }
}
</script>

<style scoped lang="scss">
.choose-community-page {
  min-height: 100vh;
  background: #fff;
  padding-bottom: 120rpx; /* 给底部按钮留空间 */
}

.header {
  display: flex;
  align-items: center;
  padding: 24rpx 24rpx 0 24rpx;
  background: #fff;
}

.city-select {
  font-size: 32rpx;
  color: #333;
  margin-right: 24rpx;
  display: flex;
  align-items: center;
}

.arrow {
  font-size: 24rpx;
  margin-left: 8rpx;
}

.search-input {
  flex: 1;
  height: 60rpx;
  border-radius: 30rpx;
  background: #f5f5f5;
  border: none;
  padding: 0 24rpx;
  font-size: 28rpx;
  color: #333;
}

.community-list {

}

.community-item {
  padding: 28rpx 24rpx;
  font-size: 30rpx;
  color: #333;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  display: flex;
  flex-direction: column;

 
}

.selected-community {
  color: $uni-color-primary;
}

.community-name {
  flex: 1;
  color: #000;
  font-size: 34rpx;
  margin-bottom: 10rpx;
}

.community-address{
  width: 100%;
  color: #999;
  font-size: 28rpx;
}

.current-tag {
  color:$uni-color-primary;
  font-size: 24rpx;
  background: rgba(74, 144, 226, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
}

.my-community {
  background: #f5f8fa;
  color: $uni-color-primary;
}

.selected {
  background: #f5f8fa;
  color: #f04c23;
}

.not-found-btn-wrapper {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 40rpx;
  display: flex;
  justify-content: center;
  z-index: 100;
}

.not-found-btn {
  background: $uni-color-primary;
  color: #fff;
  border-radius: 40rpx;
  padding: 20rpx 60rpx;
  font-size: 32rpx;
  box-shadow: 0 4rpx 16rpx rgba(240, 76, 35, 0.2);
  text-align: center;
}
.community-title{
  margin-top: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 32rpx;
  color: #333;
  background: #f5f5f5;
}
.loading-text {
  text-align: center;
  color: #999;
  font-size: 28rpx;
  padding: 20rpx 0;
}

</style>
<style lang="scss">
.choose-community-page{
input{
  background: rgba(0,0,0,0.0) !important;
  border:1px solid #f0f0f0 !important;
}
}
</style>